package com.bjsxt.service.impl;

import com.bjsxt.dubbo.DetailsDubboService;
import com.bjsxt.pojo.EsItem;
import com.bjsxt.pojo.TbItem;
import com.bjsxt.service.SearchService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author coder_z
 * @date 2023/3/19
 **/
@Service
public class SearchServiceImpl implements SearchService {
//    注入远程接口实例
    @DubboReference
    private DetailsDubboService detailsDubboService;
    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;
    @Override
    public void init() {
//    创建索引
//    在es7里所有索引操作都在indexoprations中
        IndexOperations indexOperations = elasticsearchRestTemplate.indexOps(EsItem.class);
        indexOperations.create();
//     自定义mapping
        indexOperations.putMapping(indexOperations.createMapping(EsItem.class));
//     循环分页批量新增
        int pageSize=500;
//        查询商品总条数
        Integer count=detailsDubboService.selectItemCount();
//        总页数
        int pageTotal=count%pageSize==0?count/pageSize:count/pageSize+1;
        for (int i = 0; i < pageTotal; i++) {
            List<TbItem> list = detailsDubboService.selectByPage(i, pageSize);
            ArrayList<Object> listES = new ArrayList<>();
//        执行完成后就把真正要存储到Es
            for (TbItem item : list) {
                EsItem esItem = new EsItem();
                esItem.setId(item.getId()+"");
                esItem.setImage(item.getImage());
                esItem.setPrice(item.getPrice());
                esItem.setSellPoint(item.getSellPoint());
                esItem.setTitle(item.getTitle());
//                设置商品分类
                esItem.setCatName(detailsDubboService.selectCatById(item.getCid()).getName());
//                设置商品描述
                esItem.setItemDesc(detailsDubboService.selectDescById(item.getCid()).getItemDesc());
                listES.add(esItem);
            }
        }


    }
}
